package stat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileReader;
import java.util.Map;
import java.util.TreeMap;

public class StatElem {
	
	private static Map<Integer, Integer> elems = new TreeMap<Integer, Integer>();
	
	private static void process(String str, int pos) {
		String[] tokens = str.split("\t");
		
		Integer freq = elems.get(Integer.parseInt(tokens[pos]));
		elems.put(Integer.parseInt(tokens[pos]), freq == null ? 1 : freq + 1);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		String inPath = args[0];
		String outPath = args[1];
		
		int pos = Integer.parseInt(args[2]);
		
		try {
			BufferedReader in = new BufferedReader(new FileReader(inPath));
			String str;
			
			while((str = in.readLine()) != null) {
				process(str, pos);
			}
			
			in.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter(outPath));
			
			for(Integer key : elems.keySet()) {
				out.write(key.toString());
				out.write("\t");
				out.write(elems.get(key).toString());
				out.newLine();
			}
			
			out.flush();
			out.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
